package com.yuhanginfo.modules.web.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.yuhanginfo.common.utils.SpringContextHolder;
import com.yuhanginfo.modules.web.dao.WebTransactionHistoryDao;


public class CodeUtil {
	
	private CodeUtil(){}
	private static WebTransactionHistoryDao transactionHistoryDao = SpringContextHolder.getBean(WebTransactionHistoryDao.class);;
	
	public static String getTransactionHistoryReturnCode(){
		String format = "R%03d";
		Date nowDate = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
		String now = sdf.format(nowDate);
		int transactionHistoryCode = getMaxTransactionHistoryReturnCode(now+"R");
		transactionHistoryCode = transactionHistoryCode+1;
		String a = now + format;
		return String.format(a, transactionHistoryCode);
	}
	

	public static String getTransactionHistoryCutCode(){
		String format = "C%03d";
		Date nowDate = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
		String now = sdf.format(nowDate);
		int transactionHistoryCode = getMaxTransactionHistoryCutCode(now+"C");
		transactionHistoryCode = transactionHistoryCode+1;
		String a = now+format;
		return String.format(a, transactionHistoryCode);
	}
	
	public static String getGoodsComboCode(){
		Date nowDate = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmsss");
		String now = sdf.format(nowDate);
		return String.format(now,(Math.random()*9+1)*100000);
	}
	


	private static int getMaxTransactionHistoryReturnCode(String now){
		Pattern r = Pattern.compile("(\\d+)[a-zA-Z]+(\\d+)");
		String code = transactionHistoryDao.findMaxCode(now);
		if(code!=null){
			Matcher m = r.matcher(code);
			if(m.find()){
				return Integer.parseInt(m.group(2));
			}else{
				return 0;
			}
		}else{
			return 0;
		}
	}
	
	private static int getMaxTransactionHistoryCutCode(String now){
		Pattern r = Pattern.compile("(\\d+)[a-zA-Z]+(\\d+)");
		String code = transactionHistoryDao.findMaxCode(now);
		if(code!=null){
			Matcher m = r.matcher(code);
			if(m.find()){
				return Integer.parseInt(m.group(2));
			}else{
				return 0;
			}
		}else{
			return 0;
		}
	}
	
}
